<?php

/**
 * @author zhuludong
 * @DateTime 2018.8.20
 */

/**
 * 生成唯一用户编号
 */
function uuid($prefix = '')
{
    $chars = md5(uniqid(microtime(), true));
    $uuid  = substr($chars,0,28);
    return $prefix . $uuid;
}

 /**
 * 获取redis实例
 * @param string $key redis标识
 * @return \iphp\db\Redis
 * @throws Exception
 */
function REDIS($key = '') {
    $config = C($key);
   	if(empty($config)) {
   		throw new Exception("redis 键值错误");
   	}
    return \Org\Util\Redis::getInstance($config);
}


/**
 * 获取API接口签名
 */
function get_api_sign($params=array(), $secret='epSuBIpR')
{
    $data = "";
    ksort($params);
    foreach ($params as $k => $v) {
        if (is_array($v)) {
            $v = json_encode($v);
        }
        $data .= "{$k}{$v}";
    }

    $sign = hash_hmac('md5', md5($data), $secret);

    return $sign;
}

/**
 * curl post请求 
 */
function http_post($url, $data) {
    $curlPost = $data;
    if (is_array($data) && !empty($data)) {
        $curlPost = http_build_query($data);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //设置是通过post还是get方法
    curl_setopt($ch, CURLOPT_POST, 1);
    //传递的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function i_array_column($input, $columnKey, $indexKey=null){
    if(!function_exists('array_column')){
        $columnKeyIsNumber  = (is_numeric($columnKey))?true:false;
        $indexKeyIsNull            = (is_null($indexKey))?true :false;
        $indexKeyIsNumber     = (is_numeric($indexKey))?true:false;
        $result                         = array();
        foreach((array)$input as $key=>$row){
            if($columnKeyIsNumber){
                $tmp= array_slice($row, $columnKey, 1);
                $tmp= (is_array($tmp) && !empty($tmp))?current($tmp):null;
            }else{
                $tmp= isset($row[$columnKey])?$row[$columnKey]:null;
            }
            if(!$indexKeyIsNull){
                if($indexKeyIsNumber){
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key))?current($key):null;
                    $key = is_null($key)?0:$key;
                }else{
                    $key = isset($row[$indexKey])?$row[$indexKey]:0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }else{
        return array_column($input, $columnKey, $indexKey);
    }
}